/**
 * Coryright 2015-2020 www.eyaomall.cn
 * All rights reserved.
 * @author huwenqing
 * @date 2016年10月17日
 *
 */

package com.eyaomall.wxmall.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eyaomall.wxmall.model.po.Coupon;
import com.eyaomall.wxmall.model.po.CouponGoods;
import com.eyaomall.wxmall.model.vo.CouponVO;
import com.eyaomall.wxmall.service.CouponService;
import com.github.pagehelper.StringUtil;
import com.lycheeframework.core.cmp.api.http.GsnData;
import com.lycheeframework.core.cmp.api.http.GsnResponse;
import com.lycheeframework.core.cmp.kit.PageHTTPObject;

/**
 * 优惠券
 * 
 * @author hwq
 */
@RequestMapping("coupon")
@Controller
public class CouponController {

	@Autowired
	private CouponService couponService;

	/**
	 * 对象数据
	 */
	@RequestMapping("page")
	public String couponPage(Map<String, Object> model, CouponVO coupon) {
		
		Coupon cc = couponService.queryMyGetDetail(coupon.getId());
		Coupon tt = couponService.queryDetail(coupon);
		
		model.put("coupon", tt);
		model.put("get", cc);
		
		return "home/coupon";
	}

	/**
	 * 数据读取
	 */
	@RequestMapping("page_data")
	public @ResponseBody GsnData data(Coupon coupon, PageHTTPObject pageHTTPObject) {
		
		return GsnResponse.toData(couponService.page(coupon, pageHTTPObject));
	}
	
	/**
	 * 查询我的优惠券信息
	 */
	@RequestMapping("list_my_coupon")
	public @ResponseBody GsnData listMyCoupon(CouponVO coupon) {
		List<Coupon> couponList = couponService.listMyCoupons(coupon);
		
		//查询订单中的的产品ID
		String goodsIds = coupon.getGoodsIds();
		String goodsIdArray[] = goodsIds.split(",");
		
		List<String> gList = new ArrayList<String>();
		for(String gs : goodsIdArray){
			gList.add(gs);
		}
		
		Map<Integer,Coupon> cList = new HashMap<Integer,Coupon>();
		for(Coupon cc : couponList){
			if("n".equalsIgnoreCase(cc.getEmployScope())){
				CouponVO vv = new CouponVO();
				vv.setId(cc.getId());
				
				List<CouponGoods> goodsList = couponService.listGoodsById(vv);
				
				Map<String,String> cMap = new HashMap<String,String>();
				for(CouponGoods cg : goodsList){
					String goodsId = String.valueOf(cg.getGoodsId());
					cMap.put(goodsId, goodsId);
				}
				
				for(String str : gList){
					if(StringUtil.isEmpty(cMap.get(str))){
						System.out.println(str);
						cList.put(cc.getId(),cc);
					}
				}
			}
		}
		
		List<Coupon> pp = new ArrayList<Coupon>();
		for(Coupon cp : couponList){
			if(cList.get(cp.getId()) == null){
				pp.add(cp);
			}
		}
		
		return GsnResponse.toData(pp);
	}

	/**
	 * 领取优惠券
	 */
	@RequestMapping("get_data")
	public @ResponseBody GsnData getData(Integer couponId) {
		return GsnResponse.toData(couponService.createCouponMember(couponId));
	}
}
